<template>
  <div class="templates-container">
    <div class="header">
      <h2>简历模板管理</h2>
      <el-button type="primary" @click="showDialog = true">添加模板</el-button>
    </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchQuery"
        placeholder="搜索模板名称"
        style="width: 200px"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="filteredTemplates" style="width: 100%">
      <el-table-column prop="name" label="模板名称" />
      <el-table-column prop="description" label="模板描述" show-overflow-tooltip />
      <el-table-column prop="is_default" label="默认模板">
        <template #default="scope">
          <el-tag :type="scope.row.is_default ? 'success' : 'info'">
            {{ scope.row.is_default ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" />
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            size="small" 
            type="success" 
            @click="handleSetDefault(scope.row)"
            :disabled="scope.row.is_default"
          >
            设为默认
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="showDialog"
      :title="dialogTitle"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="模板描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="10"
            placeholder="请输入模板内容（支持HTML格式）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { templateApi } from '../api'

export default {
  name: 'Templates',
  components: {
    Search
  },
  setup() {
    const formRef = ref(null)
    const templates = ref([])
    const searchQuery = ref('')
    const showDialog = ref(false)
    const dialogTitle = ref('添加模板')
    const form = ref({
      name: '',
      description: '',
      content: '',
      is_default: false
    })
    const currentId = ref(null)

    const rules = {
      name: [
        { required: true, message: '请输入模板名称', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入模板描述', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入模板内容', trigger: 'blur' }
      ]
    }

    const filteredTemplates = computed(() => {
      if (!searchQuery.value) return templates.value
      return templates.value.filter(template => 
        template.name.toLowerCase().includes(searchQuery.value.toLowerCase())
      )
    })

    const loadTemplates = async () => {
      try {
        const response = await templateApi.getAll()
        templates.value = response.data
      } catch (error) {
        ElMessage.error('加载模板列表失败')
      }
    }

    const handleSearch = () => {
      // 搜索逻辑已通过计算属性实现
    }

    const handleEdit = (row) => {
      currentId.value = row.id
      dialogTitle.value = '编辑模板'
      form.value = { ...row }
      showDialog.value = true
    }

    const handleSetDefault = async (row) => {
      try {
        await templateApi.setDefault(row.id)
        ElMessage.success('设置默认模板成功')
        loadTemplates()
      } catch (error) {
        ElMessage.error('设置默认模板失败')
      }
    }

    const handleDelete = (row) => {
      if (row.is_default) {
        ElMessage.warning('不能删除默认模板')
        return
      }
      
      ElMessageBox.confirm('确定要删除该模板吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await templateApi.delete(row.id)
          ElMessage.success('删除成功')
          loadTemplates()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
    }

    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            if (currentId.value) {
              await templateApi.update(currentId.value, form.value)
              ElMessage.success('更新成功')
            } else {
              await templateApi.create(form.value)
              ElMessage.success('添加成功')
            }
            showDialog.value = false
            loadTemplates()
          } catch (error) {
            ElMessage.error('操作失败')
          }
        }
      })
    }

    onMounted(() => {
      loadTemplates()
    })

    return {
      formRef,
      templates,
      searchQuery,
      showDialog,
      dialogTitle,
      form,
      rules,
      handleEdit,
      handleDelete,
      handleSetDefault,
      submitForm,
      filteredTemplates,
      handleSearch
    }
  }
}
</script>

<style scoped>
.templates-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  margin-bottom: 20px;
}
</style> 